package cn.niitcxl.controller;

import cn.niitcxl.domain.adminUser;
import cn.niitcxl.domain.eduMessage;
import cn.niitcxl.services.MessageServices;
import cn.niitcxl.utils.R;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/message")
public class MessageController {
    @Autowired
    private MessageServices messageServices;

    /**
     * 获取所有留言
     * @return
     */
    @GetMapping
    public R getAllMessage(){
        List<eduMessage> messageList = messageServices.list();
        return new R().ok().data("message",messageList);
    }

    /**
     * 获取所有留言带分页
     * @param currentPage
     * @return
     */
    @GetMapping("/getPage")
    public R getAllMessageByPage(@RequestParam("page") Long currentPage,
                                 @RequestParam("pageSize") Long pageSize,
                                 @RequestParam(required = false)String messageText){
      IPage<eduMessage> page =  messageServices.getPage(currentPage,pageSize,messageText);
        return new R().ok().data("page",page);
    }

    /**
     * 添加留言的方法
     * @param eduMessage
     * @return
     */
    @PostMapping("/save")
    public R saveMessage(@RequestBody(required = true) eduMessage eduMessage){
        System.out.println(eduMessage);
        if (eduMessage!=null){
            String people = eduMessage.getFromPeople();
            String message = eduMessage.getMessage();
            if(Strings.isNotEmpty(people)&&Strings.isNotEmpty(message)){
                messageServices.save(eduMessage);
                return new R().ok();
            }
            if (Strings.isEmpty(people)){
                return new R().error().message("请填写留言人名称");
            }

            if (Strings.isEmpty(message)){
                return new R().error().message("请填写留言信息");
            }
        }
        return new R().error().message("添加失败");
    }

    /**
     * 删除留言的方法
     * @param id
     * @return
     */
    @DeleteMapping
    public R deleteMessage(@RequestParam("id") int id, HttpSession session){
        //检测是否进行登陆
        adminUser userAdmin =(adminUser) session.getAttribute("userAdmin");
        if (userAdmin!=null){
            messageServices.removeById(id);
        }else {
            return new R().error();
        }
        return new R().ok();
    }
}